package org.zxyj.system.server.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zxyj.core.service.AbstractBaseServiceImpl;
import org.zxyj.system.dao.IResourceDao;
import org.zxyj.system.dao.IRoleDao;
import org.zxyj.system.domain.Resource;
import org.zxyj.system.domain.Role;
import org.zxyj.system.domain.User;
import org.zxyj.system.server.IResourceService;

/**
 * @author zhaoyong
 * @version 2016年2月19日
 */
@Service
public class ResourceServiceImpl extends AbstractBaseServiceImpl<IResourceDao, Resource>implements IResourceService {

	@Autowired
	private IRoleDao roleDao;

	public List<Resource> listUserResources(User user, String identify) {
		logger.debug("listing user's resources from DB, param: user[{}], identify[{}]", user, identify);

		if (null != user && null != user.getId()) {
			Map<String, Object> criteria = new HashMap<String, Object>();
			criteria.put("user", user);
			criteria.put("identify", identify);
			List<Role> roles = roleDao.find(criteria);
			if (!CollectionUtils.isEmpty(roles)) {
				// 根据角色查询对应的资源
				criteria = new HashMap<String, Object>();
				criteria.put("roles", roles);
				criteria.put("isShow", "YES");
				List<Resource> list = dao.find(criteria);
				getResource(list, criteria);
				return list;
			}
		}
		return null;
	}
	
	private void getResource(List<Resource> list, Map<String, Object> criteria) {
		if (list != null) {
			criteria.remove("parent");
			for (Resource resource : list) {
				criteria.put("parent", resource);
				List<Resource> children = dao.find(criteria);
				resource.setChildren(children);
				getResource(children, criteria);
			}
		}
	}

	public List<Resource> listEntitiesForBack(Map<String, Object> criteria) {
		return this.dao.findBack(criteria);
	}
	
}